package com.zz.framework.core.utils

import android.Manifest
import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import androidx.annotation.RequiresPermission
import androidx.core.app.ActivityCompat
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/4/1 11:43.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
class AudioRecorder(private val outputFile: File) {
    private companion object {
        const val SAMPLE_RATE = 44100
        const val CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO
        const val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT
    }

    private var audioRecord: AudioRecord? = null
    private var isRecording = false
    var bufferSize = 0
    init {
         bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT)
    }

    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    fun startRecording() {
        if (audioRecord==null){
            audioRecord = AudioRecord(
                MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                CHANNEL_CONFIG,
                AUDIO_FORMAT,
                bufferSize
            )
        }
        isRecording = true
        audioRecord?.startRecording()
        Thread {
            var fos: FileOutputStream? = null
            try {
                fos = FileOutputStream(outputFile)
                val bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT)
                val buffer = ByteArray(bufferSize)
                while (isRecording) {
                    val bytesRead = audioRecord?.read(buffer, 0, bufferSize) ?: 0
                    if (bytesRead > 0) {
                        // 简单的降噪处理：平均滤波
                        val denoisedBuffer = simpleDenoise(buffer)
                        fos.write(denoisedBuffer, 0, bytesRead)
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    fos?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

    fun stopRecording() {
        isRecording = false
        audioRecord?.stop()
        audioRecord?.release()
        audioRecord = null
    }

    private fun simpleDenoise(buffer: ByteArray): ByteArray {
        val denoisedBuffer = ByteArray(buffer.size)
        val windowSize = 3
        for (i in buffer.indices) {
            var sum = 0
            var count = 0
            for (j in -windowSize / 2..windowSize / 2) {
                val index = i + j
                if (index >= 0 && index < buffer.size) {
                    sum += buffer[index].toInt()
                    count++
                }
            }
            denoisedBuffer[i] = (sum / count).toByte()
        }
        return denoisedBuffer
    }
}